package com.zhentao.controller;


import cn.hutool.core.bean.BeanUtil;

import com.zhentao.utils.Result;
import com.zhentao.dto.LoginFormDTO;
import com.zhentao.dto.RegisterFormDTO;
import com.zhentao.dto.UpdateUserDTO;
import com.zhentao.dto.UserDTO;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhentao.dto.CodeRequestDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.LocalDateTime;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestBody CodeRequestDTO codeRequest, HttpSession session) {
        // 发送短信验证码并保存验证码
        return userService.sendCode(codeRequest.getPhone(), session);
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        // 实现登录功能
        return userService.login(loginForm, session);
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.fail("功能未完成");
    }

    // 兼容解析LocalDateTime
    private LocalDateTime parseLocalDateTime(String value) {
        if (value == null || value.isEmpty()) return null;
        try {
            return LocalDateTime.parse(value);
        } catch (Exception e) {
            try {
                return java.time.LocalDate.parse(value).atStartOfDay();
            } catch (Exception ignore) {}
            try {
                return LocalDateTime.parse(value.replace(" ", "T"));
            } catch (Exception ignore) {}
        }
        return null;
    }

    @GetMapping("/me")
    public Result me(@RequestHeader(value = "Authorization", required = false) String token){
        // 基于token获取当前登录的用户并返回
        if (token == null || token.isEmpty()) {
            return Result.fail("未提供认证token");
        }
        try {
            String tokenKey = "login:user:" + token;
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
            if (userMap == null || userMap.isEmpty()) {
                return Result.fail("token已过期或无效");
            }
            UserDTO userDTO = new UserDTO();
            if (userMap.get("id") != null) userDTO.setId(Integer.valueOf(userMap.get("id").toString()));
            if (userMap.get("userName") != null) userDTO.setUserName(userMap.get("userName").toString());
            if (userMap.get("nickName") != null) userDTO.setNickName(userMap.get("nickName").toString());
            if (userMap.get("phone") != null) userDTO.setPhone(userMap.get("phone").toString());
            if (userMap.get("email") != null) userDTO.setEmail(userMap.get("email").toString());
            if (userMap.get("realName") != null) userDTO.setRealName(userMap.get("realName").toString());
            if (userMap.get("portrait") != null) userDTO.setPortrait(userMap.get("portrait").toString());
            if (userMap.get("city") != null) userDTO.setCity(userMap.get("city").toString());
            if (userMap.get("gender") != null) userDTO.setGender(userMap.get("gender").toString());
            if (userMap.get("status") != null) userDTO.setStatus(userMap.get("status").toString());
            if (userMap.get("birthday") != null) userDTO.setBirthday(parseLocalDateTime(userMap.get("birthday").toString()));
            if (userMap.get("createTime") != null) userDTO.setCreateTime(parseLocalDateTime(userMap.get("createTime").toString()));
            if (userMap.get("updateTime") != null) userDTO.setUpdateTime(parseLocalDateTime(userMap.get("updateTime").toString()));
            return Result.ok(userDTO);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.fail("获取用户信息失败");
        }
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Integer userId){
        // 查询详情
        User info = userService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Integer userId){
        // 查询详情
        User user = userService.getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }

    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }

    @GetMapping("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }
    @PostMapping("/register")
    public Result register(@RequestBody RegisterFormDTO registerForm, HttpSession session) {
        return userService.register(registerForm, session);
    }
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UpdateUserDTO updateUserDTO) {
        return userService.updateUserInfo(updateUserDTO);
    }

}
